import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import { useUserStore } from "@/stores/useUserStore";

import Layout from "@/layout/Layout.vue";

const routes = [
  {
    path: "/",
    component: Layout,
    redirect: "/home",
    children: [
      {
        path: "home",
        name: "home",
        component: HomeView,
      },
      {
        path: "class",
        name: "class",
        component: import("../views/Class/Class.vue"),
      },
      {
        path: "student",
        name: "student",
        component: import("../views/Student/StudentList.vue"),
      },
      {
        path: "hw",
        name: "hw",
        component: import("../views/HW/HWList.vue"),
      },
    ],
  },
  // 查询班级指定作业的提交情况
  {
    path: "/hw/detail/:classId/:hwId",
    name: "HWDetail",
    component: import("../views/HW/HWDetail.vue"),
  },
  {
    path: "/login",
    name: "login",
    component: import("../views/Login/Login.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

router.beforeEach((to, _from, next) => {
  const infoStr = localStorage.getItem("user");
  const userStore = useUserStore();
  userStore.setInfo(JSON.parse(infoStr || "{}"));

  if (to.name !== "login" && !infoStr) {
    next({ name: "login" });
  } else {
    next();
  }
});
// routes: [
//   {
//     path: '/',
//     name: 'home',
//     component: HomeView
//   },
//   {
//     path: '/about',
//     name: 'about',
//     // route level code-splitting
//     // this generates a separate chunk (About.[hash].js) for this route
//     // which is lazy-loaded when the route is visited.
//     component: () => import('../views/AboutView.vue')
//   }
// ]

export default router;
